<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class File_manager extends Public_Controller
{
	protected $_userData = null;
	protected $_path = '';
	public function __construct()
	{
		parent::__construct();
		$this->load->library('session');
		$this->_userData = $this->session->all_userData();
		if(!isset($this->_userData['logged_in']) || !$this->_userData['logged_in']){
			redirect('./');
		}
		$this->load->model('uploking_users_m');
		$this->load->model('uploking_folders_m');
		$this->load->model('uploking_files_m');
		
		$this->load->library(array('keywords/keywords'));
		$this->load->library('form_validation');
		$this->load->helper('uploking');
		$this->lang->load('uploking');
		$this->config->load('uploking');
		$this->_path = FCPATH . $this->config->item('files_folder');
	}

	public function index()
	{
		$this->data->pages = $this->uploking_folders_m->get_page_tree($this->_userData['account']['user_id']);
		$this->data->controller =& $this;
		
		$this->template
		->title($this->module_details['name'])
		->append_metadata( js('jquery.simplemodal.js', 'file_manager') )
		->append_metadata( js('file_manager.js', 'file_manager') )
		->append_metadata( js('index.js', 'file_manager') )
		->append_metadata( css('confirm.css', 'file_manager') )
		->append_metadata( css('index.css', 'file_manager') )
		->build('file', $this->data);
	}
	
	public function search($keyword){
		$folderList = $this->uploking_folders_m->like('name', $keyword)->get_many_by(array(
			'user_id' 		=> $this->_userData['account']['user_id']
		));
		
		$fileList = $this->uploking_files_m->like('name', $keyword)->get_many_by(array(
			'user_id' 		=> $this->_userData['account']['user_id']
		));
		
		if(!$this->input->is_ajax_request()){
			redirect('./');
		}
		$this->input->is_ajax_request() ? $this->template->set_layout(FALSE) : '';
		
		$fileIconList = $this->config->item('file_icon_list');
		$this->template
			->title($this->module_details['name'])
			->set('folderList', $folderList)
			->set('fileList', $fileList)
			->set('fileIconList', $fileIconList)
			->build('list_file', $this->data);
	}
	public function share(){
		if(!$this->input->is_ajax_request()){
			redirect('./');
		}
		if($this->input->post('action')){
			$emails = $this->input->post('emais');
			$description = $this->input->post('description');
			$result = array();
			$fileIdList = $this->input->post('file_id');
			$folderIdList = $this->input->post('folder_id');
			$fileList = array();
			if($fileIdList){
				$fileList = $this->uploking_files_m->where_in('id', $fileIdList)->get_many_by('user_id', $this->_userData['account']['user_id']);	
			}
			if($folderIdList){
				$fileList = $this->uploking_files_m->where_in('folder_id', $folderIdList)->get_many_by('user_id', $this->_userData['account']['user_id']);	
			}
			
			if($fileList){
				foreach ($fileList as $file){
					$this->uploking_files_m->update($file->id, array(
						'share_desc'	=> $description 
					));
				}
				$links = '';
				if($fileList){
					foreach ($fileList as $file){
						$links .= '<a href="'.site_url().'myfiles/index/'.$file->id.'">'.site_url().'myfiles/index/'.$file->id.'</a><br/>';
					}
				}
				$this->load->library('email');

				$this->email->from($this->_userData['account']['email'], 'Share links');
				$this->email->to($emails);
				$this->email->subject('Share links');
				$this->email->message($description.'<br/>'.$links);
				$this->email->send();
			}
			$result['result'] = true;
			echo json_encode($result);
			
		}else{
			$fileIdList = $this->input->post('file_id');
			$folderIdList = $this->input->post('folder_id');
			$fileList = array();
			if($fileIdList){
				$fileList = $this->uploking_files_m->where_in('id', $fileIdList)->get_many_by('user_id', $this->_userData['account']['user_id']);	
			}
			if($folderIdList){
				$fileList = $this->uploking_files_m->where_in('folder_id', $folderIdList)->get_many_by('user_id', $this->_userData['account']['user_id']);	
			}
			
			$this->input->is_ajax_request() ? $this->template->set_layout(FALSE) : '';
			
			$this->template
			->title($this->module_details['name'])
			->set('fileList', $fileList)
			->build('share', $this->data);
		}
	}
	public function list_file($folderId = 0){
		$folderList = $this->uploking_folders_m->get_many_by(array(
			'user_id' 		=> $this->_userData['account']['user_id'],
			'parent_id'		=> $folderId
		));
		$this->session->set_userdata('current_folder_id', $folderId);
		$fileList = $this->uploking_files_m->get_many_by(array(
			'user_id' 		=> $this->_userData['account']['user_id'],
			'folder_id'		=> $folderId
		));
		
		if(!$this->input->is_ajax_request()){
			redirect('./');
		}
		$this->input->is_ajax_request() ? $this->template->set_layout(FALSE) : '';
		
		$fileIconList = $this->config->item('file_icon_list');
		$this->template
			->title($this->module_details['name'])
			->set('folderList', $folderList)
			->set('fileList', $fileList)
			->set('fileIconList', $fileIconList)
			->build('list_file', $this->data);
	}
	
	function new_folder(){
		if(!$this->input->is_ajax_request()){
			redirect('./');
		}
		if($this->input->post('action')){
			$result = array();
			$folderName = trim($this->input->post('folderName'));
			if($folderName){
				if(isset($this->_userData['current_folder_id'])){
					$current_folder_id = $this->_userData['current_folder_id'];
				}else{
					$current_folder_id = 0;
				}
				$id = $this->uploking_folders_m->insert(array(
					'user_id'			=> $this->_userData['account']['user_id'],
					'parent_id'			=> $current_folder_id,
					'name'				=> $folderName,
					'created_on'		=> time(),
					'order'				=>  0
				
				));
				$result['result']= true;
				$result['id']= $id;
				$result['current_folder_id']= $current_folder_id;
				$result['name']= $folderName;
				echo json_encode($result);				
			}else{
				$result['result']= false;
				$result['message']= lang('uploking_new_folder_require_label');
				echo json_encode($result);
			}			
		}else{
			$this->input->is_ajax_request() ? $this->template->set_layout(FALSE) : '';
			
			$this->template
			->title($this->module_details['name'])
			->build('new_folder', $this->data);
		}
	}
	public function move_action(){
		$result = array();
		$desId = $this->input->post('desId');
		if($desId){
			$result['desId'] = $desId;
			$folderIdList = $this->input->post('folder_id');
			if($folderIdList){
				foreach ($folderIdList as $folderId){
					$this->uploking_folders_m->where('user_id', $this->_userData['account']['user_id'])->update($folderId, array(
						'parent_id'		=> $desId
					));
				}
			}
			$fileIdList = $this->input->post('file_id');
			if($fileIdList){
				foreach ($fileIdList as $fileId){
					$this->uploking_files_m->where('user_id', $this->_userData['account']['user_id'])->update($fileId, array(
						'folder_id'		=> $desId
					));
				}
			}
			$result['result'] = true;
		}else{
			$result['result'] = false;
		}
		echo json_encode($result);
	} 
	public function copy_action(){
		$folder = uploking_getFolderName();
		$uploadDir = $this->_path;
		$targetDir = $this->_path . DIRECTORY_SEPARATOR . $folder;
		if (!file_exists($targetDir))
		@mkdir($targetDir);
		
		$result = array();
		$desId = $this->input->post('desId');
		if($desId){
			$result['desId'] = $desId;
			$folderIdList = $this->input->post('folder_id');
			if($folderIdList){
				foreach ($folderIdList as $folderId){
					$this->uploking_folders_m->update($folderId, array(
						'parent_id'		=> $desId
					));
				}
			}
			$fileIdList = $this->input->post('file_id');
			if($fileIdList){
				foreach ($fileIdList as $fileId){
					$fileData = $this->uploking_files_m->where('user_id', $this->_userData['account']['user_id'])->get($fileId);
					
					$fileName = $fileData->filename;
					//$this->uploking_files_m
					$ext = strrpos($fileName, '.');
					$fileName_a = substr($fileName, 0, $ext);
					$fileName_b = substr($fileName, $ext);
		
					$count = 1;
					while (file_exists($targetDir. $fileName_a . '_' . $count . $fileName_b))
					$count++;
					$fileName = $fileName_a . '_' . $count . $fileName_b;
					if(copy($uploadDir . DIRECTORY_SEPARATOR. $fileData->folder. DIRECTORY_SEPARATOR .$fileData->filename, $targetDir . DIRECTORY_SEPARATOR .$fileName)){
						$this->uploking_files_m->insert(array(
						'folder_id'	=> $desId,
						'user_id'	=> $this->_userData['account']['user_id'],
						'type'		=> $fileData->type,
						'name'		=> $fileData->name,
						'filename'	=> $fileName,
						'folder'	=> $folder,
						'extension'	=> $fileData->extension,
						'mimetype'	=> $fileData->mimetype,
						'filesize'	=> $fileData->filesize,
						'date_added'=> time(),
						'sort'		=> 0
						));
					}
					
					
				}
			}
			$result['result'] = true;
		}else{
			$result['result'] = false;
		}
		echo json_encode($result);
	}
	function edit_folder($id){
		if(!$this->input->is_ajax_request()){
			redirect('./');
		}
		$folder = $this->uploking_folders_m->get($id);
		if($this->input->post('action')){
			$result = array();
			$folderName = trim($this->input->post('folderName'));
			if($folderName){
				$this->uploking_folders_m->update($id, array(
					'name'				=> $folderName
				));
				$result['result']= true;
				$result['id']= $id;
				$result['folderName'] = $folderName;
				echo json_encode($result);				
			}else{
				$result['result']= false;
				$result['message']= lang('uploking_new_folder_require_label');
				echo json_encode($result);
			}			
		}else{
			$this->input->is_ajax_request() ? $this->template->set_layout(FALSE) : '';
			$this->template
			->title($this->module_details['name'])
			->set('folder', $folder)
			->build('edit_folder', $this->data);
		}
	}
	function edit_file($id){
		if(!$this->input->is_ajax_request()){
			redirect('./');
		}
		$file = $this->uploking_files_m->get($id);
		if($this->input->post('action')){
			$result = array();
			$fileName = trim($this->input->post('fileName'));
			if($fileName){
				$this->uploking_files_m->update($id, array(
					'name'				=> $fileName
				));
				$result['result']= true;
				$result['id']= $id;
				$result['fileName'] = $fileName;
				echo json_encode($result);				
			}else{
				$result['result']= false;
				$result['message']= lang('uploking_new_file_require_label');
				echo json_encode($result);
			}			
		}else{
			$this->input->is_ajax_request() ? $this->template->set_layout(FALSE) : '';
			$this->template
			->title($this->module_details['name'])
			->set('file', $file)
			->build('edit_file', $this->data);
		}
	}
	public function folder_box(){
		if(!$this->input->is_ajax_request()){
			redirect('./');
		}
		$this->data->pages = $this->uploking_folders_m->get_page_tree($this->_userData['account']['user_id']);
		$this->data->controller =& $this;
		
		$this->input->is_ajax_request() ? $this->template->set_layout(FALSE) : '';
		
		$this->template
		->title($this->module_details['name'])
		->build('folder_box', $this->data);
	}
	public function delete_action(){
		$result = array();
		$fileIdList = $this->input->post('file_id');
		$folderIdList = $this->input->post('folder_id');
		if($fileIdList){
			foreach ($fileIdList as $fileId){
				$fileData = $this->uploking_files_m->get($fileId);
				if($fileData){
					$this->uploking_files_m->delete_by(array(
						'id'	=> $fileId,
						'user_id'	=> $this->_userData['account']['user_id']
					));
					if(file_exists($this->_path . DIRECTORY_SEPARATOR. $fileData->folder. DIRECTORY_SEPARATOR . $fileData->filename)){
						unlink($this->_path . DIRECTORY_SEPARATOR. $fileData->folder. DIRECTORY_SEPARATOR . $fileData->filename);					
					}
				}
			}
		}
		if($folderIdList){
			foreach ($folderIdList as $folderId){
				$this->delete_folder($folderId);
			}
		}
		$result['result'] = true;
		echo json_encode($result);
	}
	
	protected function delete_folder($id){
		$this->uploking_folders_m->delete_by(array(
			'id'		=> $id,
			'user_id'	=> $this->_userData['account']['user_id']
		));
		
		$fileList = $this->uploking_files_m->get_many_by(array(
			'folder_id'		=> $id,
			'user_id'		=> $this->_userData['account']['user_id']
		));
		if($fileList){
			foreach ($fileList as $file) {
				$this->uploking_files_m->delete_by(array(
					'id'	=> $file->id,
					'user_id'	=> $this->_userData['account']['user_id']
				));
				if(file_exists($this->_path . DIRECTORY_SEPARATOR. $file->folder. DIRECTORY_SEPARATOR . $file->filename)){
					unlink($this->_path . DIRECTORY_SEPARATOR. $file->folder. DIRECTORY_SEPARATOR . $file->filename);					
				}
				
			}
		} 
		
		$subFolderList = $this->uploking_folders_m->get_many_by('parent_id', $id);
		if($subFolderList){
			foreach ($subFolderList as $subFolder){
				$this->delete_folder($subFolder->id);
			}
		}else{
			return;
		}
	}
	
	public function order()
	{
		$order	= $this->input->post('order');
		$data	= $this->input->post('data');
		$root_pages	= isset($data['root_pages']) ? $data['root_pages'] : array();

		if (is_array($order))
		{
			//reset all parent > child relations
			$this->uploking_folders_m->update_all(array('parent_id' => 0));

			foreach ($order as $i => $page)
			{
				//set the order of the root pages
				$this->uploking_folders_m->update_by('id', str_replace('page_', '', $page['id']), array('order' => $i));

				//iterate through children and set their order and parent
				$this->uploking_folders_m->_set_children($page);
			}

			// rebuild page URIs
			//$this->uploking_folders_m->update_lookup($root_pages);

			$this->pyrocache->delete_all('navigation_m');
			$this->pyrocache->delete_all('uploking_folders_m');
			Events::trigger('post_page_order', array($order, $root_pages));
		}
	}
	
	public function tree_builder($page)
	{
		if (isset($page['children'])):

			foreach($page['children'] as $page): ?>

				<li id="page_<?php echo $page['id']; ?>">
					<div>
						<!-- <a href="#" rel="<?php echo $page['id'] . '">' . $page['name']; ?></a>  -->
						<a href="#" rel="<?php echo $page['id']?>"><?php echo $page['name']; ?></a>
					</div>

			<?php if(isset($page['children'])): ?>
					<ul>
							<?php $this->tree_builder($page); ?>
					</ul>
				</li>
			<?php else: ?>
				</li>
			<?php endif;
			endforeach;
		endif;
	}
	
}
